﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Contains forum name, its associated table name, and forum description.
/// </summary>
public class Forum
{
    private ForumDatabaseAdapter DatabaseAdapater { get; set; }
    public string ForumName { get; set; }
    public string TableName { get; set; }
    public string Description { get; set; }
    private List<ForumEntry> ForumEntryList { get; set; }

    public const string FORUM_LIST_TABLE = "ForumListTable";
    public const string COLUMN_FORUM_NAME = "ForumName";
    public const string COLUMN_TABLE_NAME = "TableName";
    public const string COLUMN_DESCRIPTION = "Description";

    // used as a constant
    public static string[] FORUM_LIST_COLUMNS = {   string.Format("{0} nvarchar(50)", COLUMN_FORUM_NAME), 
                                                    string.Format("{0} nvarchar(50)", COLUMN_TABLE_NAME), 
                                                    string.Format("{0} nvarchar(MAX)", COLUMN_DESCRIPTION) };

	public Forum()
	{
        
	}

    public Forum(string forumName, string tableName, string description)
    {
        this.ForumName = forumName;
        this.TableName = tableName;
        this.Description = description;
    }

    private bool DoesTableExist(string tableName)
    {
        DatabaseAdapater = new ForumDatabaseAdapter();
        DatabaseAdapater.Open();
        bool doesTableExists = DatabaseAdapater.DoesTableExist(tableName);
        DatabaseAdapater.Close();

        return doesTableExists;
    }
    
    /// <summary>
    /// Create a forum by creating inserting the table name in table ForumListTable
    /// and creating a new table for the forum
    /// </summary>
    public void CreateForum()
    {
        CreateForumListTable();
        CreateNewForumTable();
    }

    private void CreateNewForumTable()
    {
        if (!DoesTableExist(this.TableName))
        {
            DatabaseAdapater = new ForumDatabaseAdapter();
            DatabaseAdapater.Open();
            DatabaseAdapater.CreateTable(this.TableName, FORUM_LIST_COLUMNS);
            DatabaseAdapater.InsertToForumList(this.ForumName, this.TableName, this.Description);
            DatabaseAdapater.Close();
        }
    }

    private void CreateForumListTable()
    {
        if (!DoesTableExist(FORUM_LIST_TABLE))
        {
            DatabaseAdapater = new ForumDatabaseAdapter();
            DatabaseAdapater.Open();
            DatabaseAdapater.CreateTable(FORUM_LIST_TABLE, FORUM_LIST_COLUMNS);
            DatabaseAdapater.Close();
        }
    }

    /// <summary>
    /// Returns forum name
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return ForumName;
    }
}